import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from "../utils/cookie"
import store from '../store/index'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Index',
        component: () => import('../views/IndexPage'),
        meta: {
            title: '首页'
        },
        children: [
            {
                path: '',
                redirect: 'home'
            },
            {
                path: 'home',
                name: 'Home',
                component: () => import('../views/HomePage'),
                meta: {
                    title: '首页'
                }
            },
            {
                path: 'all-store',
                name: 'AllStore',
                component: () => import('../views/AllStore'),
                meta: {
                    title: '全部商品'
                }
            },
            {
                path: 'about-us',
                name: 'AboutUs',
                component: () => import('../views/AboutUs'),
                meta: {
                    title: '关于我们'
                }
            },
            {
                path: 'all-store/details/:id',
                name: 'Details',
                component: () => import('../components/GoodsDetail'),
                meta: {
                    title: '详情'
                }
            },
            {
                path: 'my-tips',
                name: 'MyTips',
                component: () => import('../components/MyTips'),
                meta: {
                    title: '我的订单'
                }
            },
            {
                path: 'my-collection',
                name: 'MyCollection',
                component: () => import('../components/MyCollection'),
                meta: {
                    title: '我的收藏'
                }
            },
            {
                path: 'my-shop',
                name: 'MyShop',
                component: () => import('../components/MyShop'),
                meta: {
                    title: '我的购物车'
                }
            }

        ]
    }

]

const router = new VueRouter({
    mode: 'history',
    routes
})

router.beforeEach((to, from, next) => {
    if (getToken('token')) {
        if (!store.state.userShoppingCarNum) {
            store.dispatch("getUserInfo");
        }
        next()
    } else {
        if (to.path.includes('/home') || to.path.includes('/all-store') || to.path.includes('/about-us')) {
            return next()
        }
        alert("请先登录！")
        next({
            path: '/home'
        })
    }
    next()
})

export default router
